<template>
  <a-card :bordered="false" :bodyStyle="{ padding: 0 }">
    <a-row style="display:flex;">
      <a-col :xs="12" :md="6" :lg="6">
        <a-spin :spinning="loading">
          <div>
            <span style="float: left;margin-left:8px;margin-top:7px; ">{{ $t('menu.dict') }}</span>
            <a-button v-action:add style="float: right;margin-top: 2px;" type="link" @click="handleDictModalOpen()">{{
              $t('button.add')
            }}</a-button>
          </div>
          <a-input-search
            :placeholder="$t('common.query')"
            v-model="searchKey"
            style="padding:8px;"
            @search="onDictSearch"
            allowClear
          />
          <a-list bordered size="small" :data-source="dictClassList" class="dictClassList">
            <a-list-item
              :class="{ selected: selectedNode && selectedNode.id === item.id }"
              slot="renderItem"
              slot-scope="item"
              @click="handleDictClassClick(item)"
            >
              <div class="dict-list-item">
                <div class="dict-list-item-item" :title="`${item.code} | ${item.name}`">
                  {{ item.code + ' | ' + item.name }}
                </div>
                <div v-action:edit|delete>
                  <a-dropdown :trigger="['hover']">
                    <a class="ant-dropdown-link" href="javascript:;"><a-icon type="more" /> </a>
                    <a-menu slot="overlay" @click="({ key }) => onClickTypeDropdown(key, item)">
                      <a-menu-item v-action:edit key="edit"> <a-icon type="edit" />{{ $t('common.edit') }}</a-menu-item>
                      <a-menu-item v-action:delete key="delete">
                        <a-icon type="delete" />{{ $t('common.delete') }}
                      </a-menu-item>
                    </a-menu>
                  </a-dropdown>
                </div>
              </div>
            </a-list-item>
          </a-list>
        </a-spin>
      </a-col>
      <a-col
        :xs="12"
        :md="18"
        :lg="18"
        style=" border-left: 1px solid #e8e8e8;padding: 20px;"
        :style="{ minHeight: `${layoutContentHeight - pageHeaderHeight + 20}px` }"
      >
        <a-spin :spinning="loading">
          <a-descriptions v-if="!!selectedNode">
            <a-descriptions-item :label="$t('common.code').toLowerCase()">
              {{ selectedNode.code }}
            </a-descriptions-item>
            <a-descriptions-item :label="$t('common.name').toLowerCase()">
              {{ selectedNode.name }}
            </a-descriptions-item>
            <a-descriptions-item :label="$t('common.description').toLowerCase()">
              {{ selectedNode.description }}
            </a-descriptions-item>
            <a-descriptions-item :label="$t('common.createUser').toLowerCase()">
              {{ selectedNode.createBy }}
            </a-descriptions-item>
            <a-descriptions-item :label="$t('common.createTime').toLowerCase()">
              {{ $options.filters.moment(selectedNode.createDate) }}
            </a-descriptions-item>
            <a-descriptions-item :label="$t('common.editor').toLowerCase()">
              {{ selectedNode.modifyBy }}
            </a-descriptions-item>
            <a-descriptions-item :label="$t('common.modifyTime').toLowerCase()">
              {{ $options.filters.moment(selectedNode.modifyDate) }}
            </a-descriptions-item>
          </a-descriptions>
          <!-- 右侧详情 end -->
          <a-divider v-show="!!selectedNode" />
          <!-- 右侧table搜索栏 start -->
          <div v-show="!!selectedNode || searchFlag">
            <a-input
              placeholder="全局查找数据字典"
              style="width:150px;margin-right: 10px"
              class="search-btn"
              v-model.trim="searchDictKey"
            />
            <a-button
              class="search-btn"
              type="primary"
              icon="search"
              @click="handleSearchDictDetail"
            >{{ $t('common.query') }}
            </a-button>
            <a-button class="search-btn" icon="reload" @click="reset">{{ $t('common.reset') }}</a-button>
            <a-button
              v-action:add
              v-show="!!selectedNode"
              class="search-btn"
              type="primary"
              icon="plus"
              @click="handleDictDetailModal()"
            >{{
              $t('common.addNewRecord', {
                name: this.$t('technology.dict.dictDetail').toLowerCase()
              })
            }}</a-button
            >
          </div>
          <!-- 右侧table搜索栏 end -->
          <!-- 右侧table start -->
          <a-table
            :loading="tableLoading"
            v-show="!!selectedNode || searchFlag"
            ref="table"
            rowKey="id"
            :columns="columns"
            :data-source="tableData"
            :pagination="false"
            :scroll="{ x: tableWidth }"
          >
            <span slot="action" slot-scope="text, record">
              <a-popconfirm
                :title="$t('common.delWarning', { name: $t('technology.dict.dictDetail') })"
                :okText="$t('common.ok')"
                :cancelText="$t('common.cancel')"
                @confirm="handleDeleteDetail(record.id)"
              >
                <a v-action:delete href="#" class="link-danger">{{ $t('common.delete') }}</a>
              </a-popconfirm>
            </span>
          </a-table>
          <!-- 右侧table start -->
        </a-spin>
      </a-col>
    </a-row>
    <!--    字典分类表单-->
    <dict-class-form ref="dictClassForm" @ok="handleDictClassFormOk" />
    <!--    字典明细表单-->
    <dict-detail-form ref="dictDetailForm" @ok="handleDictDetailFormOk" />
  </a-card>
</template>

<script>
import { ResizableGrid } from '@/components'
import { layoutMixin, resizableMixin } from '@/utils/mixin'
import {
  getDictClassList,
  delDictClass,
  getDictDetailList,
  delDictDetail,
  getDictDetailListByClassCode
} from '@/api/technology/dict/dict'
import DictClassForm from '@/views/technology/dict/modules/DictClassForm'
import DictDetailForm from '@/views/technology/dict/modules/DictDetailForm'

export default {
  name: 'DictSetting',
  mixins: [layoutMixin, resizableMixin],
  components: {
    ResizableGrid,
    DictClassForm,
    DictDetailForm
  },
  data () {
    return {
      searchKey: '',
      searchDictKey: '',
      searchFlag: '',
      tableData: [],
      tableLoading: false,
      loading: false,
      dictClassList: [],
      detailList: [],
      dictClassInfo: {},
      // 当前选择树节点
      selectedNode: null
    }
  },
  computed: {
    // 最终显示字段
    columns () {
      let colums = [
        {
          title: this.$t('common.index'),
          dataIndex: 'index',
          width: 80,
          customRender: (text, record, index) => index + 1
        },
        {
          title: this.$t('technology.dict.dictCode'),
          dataIndex: 'techDataDictionaryCode',
          width: 120,
          ellipsis: true
        },
        {
          title: this.$t('technology.dict.dictName'),
          dataIndex: 'techDataDictionaryName',
          width: 120,
          ellipsis: true
        },
        {
          title: this.$t('technology.dict.key'),
          dataIndex: 'key',
          width: 120,
          ellipsis: true
        },
        {
          title: this.$t('technology.dict.value'),
          dataIndex: 'value',
          width: 120,
          ellipsis: true
        },
        {
          title: this.$t('common.description'),
          dataIndex: 'description',
          width: 150,
          ellipsis: true
        },
        {
          title: this.$t('common.editor'),
          dataIndex: 'modifyBy',
          width: 100,
          ellipsis: true
        },
        {
          title: this.$t('common.modifyTime'),
          dataIndex: 'modifyDate',
          width: 150,
          ellipsis: true,
          customRender: date => (date ? this.$options.filters.moment(date) : '')
        }
      ]
      if (this.$auth('delete', this.$route.meta.permissionId)) {
        colums = colums.concat({
          title: this.$t('common.action'),
          fixed: 'right',
          width: 100,
          align: 'center',
          scopedSlots: {
            customRender: 'action'
          }
        })
      }
      return colums
    },
    tableWidth () {
      const width = this.columns.reduce((last, next) => {
        last += next.width
        return last
      }, 0)
      return width
    }
  },
  created () {
    this.init()
  },
  methods: {
    /**
     * 获取左侧树
     */
    init () {
      const params = {
        searchKey: this.searchKey
      }
      getDictClassList(params)
        .then(res => {
          this.loading = true
          const { data } = res
          this.dictClassList = data
        })
        .finally(() => {
          this.loading = false
        })
    },
    handleDictClassClick (item) {
      this.selectedNode = item
      this.searchFlag = ''
      this.loadTableData()
    },
    loadTableData () {
      const req = {}
      if (this.searchFlag === 'search') {
        // 全局搜索
        req.searchKey = this.searchDictKey
        this.tableLoading = true
        getDictDetailList(req)
          .then(res => (this.tableData = res.data))
          .finally(() => {
            this.tableLoading = false
          })
      } else {
        if (!this.selectedNode) return
        req.code = this.selectedNode.code
        getDictDetailListByClassCode(req)
          .then(res => (this.tableData = res.data))
          .finally(() => {
            this.tableLoading = false
          })

        // 根据字典搜索明细
      }
    },
    onClickTypeDropdown (key, item) {
      switch (key) {
        case 'new':
          this.handleDictModalOpen()
          break
        case 'edit':
          this.handleDictModalOpen(item)
          break
        case 'delete': {
          const name = this.$t('menu.dict')
          this.$confirm({
            title: this.$t('common.warning'),
            content: this.$t('common.delWarning', {
              name: name.toLowerCase()
            }),
            onOk: () => {
              delDictClass([item.id]).then(res => {
                if (res.code === 'sso.ok') {
                  this.$message.success(this.$t(res.message))
                  this.init()
                }
              })
            }
          })
          break
        }
        default:
      }
    },

    handleSearchDictDetail () {
      this.selectedNode = null
      this.searchFlag = 'search'
      this.loadTableData()
    },
    // 字典分类新增编辑
    handleDictModalOpen (item) {
      const form = this.$refs.dictClassForm
      if (!item) {
        form.add(item)
      } else {
        form.edit(item)
      }
    },
    handleDictDetailModal (item) {
      const form = this.$refs.dictDetailForm
      if (!item) {
        form.add(this.selectedNode)
      } else {
        form.edit(item)
      }
    },
    onDictSearch () {
      this.init()
    },

    /**
     * 列表重置
     */
    reset () {
      this.selectedNode = null
      this.searchDictKey = ''
      this.searchFlag = 'search'
      this.loadTableData()
    },

    /**
     * 获取table列表
     */

    /**
     * table 操作 删除detail
     */
    handleDeleteDetail (id) {
      delDictDetail([id]).then(res => {
        this.$message.success(res.message)
        this.loadTableData()
      })
    },

    /**
     * 弹窗编辑回调
     */
    handleDictClassFormOk () {
      this.init()
    },
    handleDictDetailFormOk () {
      this.loadTableData()
    }
  }
}
</script>
<style lang="less" scoped>
.search-btn {
  margin: 0 8px 8px 0;
}
.listItem {
  display: inline-block;
}

.dict-list-item {
  width: 100%;
  display: flex;
  justify-content: space-between;
  .dict-list-item-item {
    width: 80%;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    display: block;
  }
}
.ant-list-item {
  &:hover {
    background-color: #e6f7ff;
    color: rgba(0, 0, 0, 0.65);
  }
  &.selected {
    background-color: #1890ff;
    color: #fff;
  }
}
.selected {
  background-color: #1890ff;
  & /deep/ a {
    color: #fff;
  }
}
.ant-list-bordered {
  border-right-width: 0px;
  border: none;
}
/deep/.ant-descriptions-item-content {
  word-break: break-all;
}
</style>
